<template>
  <div id="pub_work_main">
    <div id="left">
      <el-form class="pub_work_form" ref="form" :model="form" label-width="80px">
        <el-form-item label="班级">
          <el-select v-model="class_value" placeholder="请选择班级">
            <el-option v-for="item in class_options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科目">
          <el-select v-model="work_value" placeholder="请选择科目">
            <el-option v-for="item in work_options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作业内容">
          <el-input v-model="form.context" placeholder="请输入作业内容" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-col :span="11">
            <el-date-picker type="datetime" placeholder="选择日期" v-model="form.endline" style="width: 100%;"
              @change="checkDate"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="附件">
          <input class="el-select" ref="fileInput" type="file" @change="handleFileChange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">发布作业</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="right">
      <h1>
        作业完成情况 <a href="" @click.prevent="refresh">刷新</a>
      </h1>

      <div v-for="item in homeworkData" :key="item.subjectName">
        <h2>{{ item.subjectName }}</h2>
        <el-table :data="item.tableData" max-height="500" :row-class-name="tableRowClassName" @row-click="openDialog"
          border>
          <el-table-column prop="expId" label="作业编号" width="100">
          </el-table-column>
          <el-table-column fixed prop="userId" label="学号" width="100">
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="100">
          </el-table-column>
          <el-table-column prop="homeworkId" label="作业编号" width="180">
          </el-table-column>
          <el-table-column prop="subjectId" label="科目编号" width="180">
          </el-table-column>
          <el-table-column prop="subjectName" label="科目名称" width="180">
          </el-table-column>
          <el-table-column prop="remark" label="作业内容" width="180">
            <!-- <template slot-scope="scope">
              <div @click="openDialog(scope.row)">点击查看</div>
            </template> -->
          </el-table-column>
          <el-table-column prop="subDate" label="作业发布时间" width="180">
          </el-table-column>
          <el-table-column prop="status" label="作业完成状态" width="180">
          </el-table-column>
          <el-table-column prop="grade" label="得分" width="180">
          </el-table-column>
          <el-table-column prop="comments" label="评语" width="180">
          </el-table-column>
          <el-table-column prop="endline" label="截止时间" width="180">
          </el-table-column>
          <el-table-column prop="completeTime" label="作业提交时间" width="180">
          </el-table-column>
        </el-table>
      </div>
      <el-button type="text" @click="dialogVisible = true">统计未完成名单</el-button>
      <el-dialog title="未完成名单" :visible.sync="dialogVisible" width="30%">
        <div class="uncomplete-dialog-content">
          <div v-for="item in unCompleteData" :key="item.subjectName">
            <h3>{{ item.subjectName }} (未提交人数: {{ item.tableData.length }})</h3>
            <el-table :data="item.tableData" max-height="200" border>
              <el-table-column fixed prop="userId" label="学号" width="100">
              </el-table-column>
              <el-table-column prop="username" label="姓名" width="100">
              </el-table-column>
              <el-table-column prop="homeworkId" label="作业编号" width="180">
              </el-table-column>
              <el-table-column prop="subjectId" label="科目编号" width="180">
              </el-table-column>
              <el-table-column prop="subjectName" label="科目名称" width="180">
              </el-table-column>
              <el-table-column prop="remark" label="作业内容" width="180">
              </el-table-column>
              <el-table-column prop="subDate" label="作业发布时间" width="180">
              </el-table-column>
              <el-table-column prop="status" label="作业完成状态" width="180">
              </el-table-column>
              <el-table-column prop="grade" label="得分" width="180">
              </el-table-column>
              <el-table-column prop="comments" label="评语" width="180">
              </el-table-column>
              <el-table-column prop="endline" label="截止时间" width="180">
              </el-table-column>
            </el-table>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑作业信息的对话框 -->
      <el-dialog title="作业信息" :visible.sync="dialogFormVisible" width="50%">
        <el-form :model="dialogForm" label-width="100px">
          <el-form-item label="作业编号">
            <el-input v-model="dialogForm.expId" disabled></el-input>
          </el-form-item>
          <el-form-item label="学号">
            <el-input v-model="dialogForm.userId" disabled></el-input>
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="dialogForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="作业内容">
            <el-input v-model="dialogForm.remark" type="textarea" disabled></el-input>
          </el-form-item>
          <el-form-item label="提交状态">
            <el-input v-model="dialogForm.status" disabled></el-input>
          </el-form-item>
          <el-form-item label="完成时间">
            <el-input v-model="dialogForm.completeDate" disabled></el-input>
          </el-form-item>
          <el-form-item label="得分">
            <el-input placeholder="请为这位学生打分" style="width: 92%;" v-model="dialogForm.grade"></el-input>
            <span>
              /{{ dialogForm.totalGrade }}分
            </span>
          </el-form-item>
          <el-form-item label="评语">
            <el-input placeholder="请客观地评价这位学生的作业" v-model="dialogForm.comments" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="附件">
            <a href="" @click.prevent="getCompleteFile">{{ dialogForm.fileCompletePath }}</a>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script scoped>
import { getFile, getStudentsHomeworks, pubComments, putFile } from '@/utils/urlManager'
import axios from 'axios'
import '@/utils/InterceptorUtils'

export default {
  data() {
    return {
      unCompleteData: [],
      homeworkData: [
        {
          subjectName: '', // 课程名
          tableData: [{   // 作业完成信息
            userId: '',
            username: '',
            homeworkId: '',
            subjectId: '',
            subjectName: '',
            subDate: '',
            status: '',
            grade: '',
            comments: '',
            endline: '',
            completeTime: '',
            remark: ''
          }],
        }
      ],
      file: null,
      form: {
        classId: '',
        endline: '',
        homeworkId: '',
        context: ''
      },
      class_options: [],
      class_value: '',
      work_options: [
        {
          value: 'homework_001',
          label: '软件工程'
        }, {
          value: 'homework_002',
          label: '计算机程序设计'
        }, {
          value: 'homework_003',
          label: '数据结构与算法'
        }, {
          value: 'homework_004',
          label: '操作系统'
        }, {
          value: 'homework_005',
          label: 'MySQL数据库'
        }, {
          value: 'homework_006',
          label: 'HTML基础'
        }, {
          value: 'homework_007',
          label: '编译原理'
        }, {
          value: 'homework_008',
          label: 'Java基础'
        }, {
          value: 'homework_009',
          label: '软件测试'
        }, {
          value: 'homework_010',
          label: 'C语言基础'
        }
      ],
      work_value: '',
      dialogVisible: false,
      unCompletelNums: 0,
      dialogFormVisible: false, // 对话框显示状态
      dialogForm: { // 对话框表单数据
        expId: '',
        classId: '',
        userId: '',
        username: '',
        remark: '',
        grade: '',
        comments: '',
        completeDate: '',
        fileCompletePath: '',
        homeworkName: '',
        totalGrade: ''
      },
      cdTime: 3000
    };
  },
  mounted() {
    this.getClassId();
    if (localStorage.getItem("isGet") == "true") {
      this.get();
    } else {
      this.homeworkData = JSON.parse(localStorage.getItem("homeworkData"));
      this.unCompleteData = JSON.parse(localStorage.getItem("unCompleteData"));
    }
  },
  methods: {
    refresh() {
      const now = new Date().getTime(); // 获取当前时间戳

      // 检查是否满足最短间隔时间
      if (now - this.lastRefreshTime < this.cdTime) {
        this.$message.warning("操作太频繁啦，请稍后再试！");
        return; // 如果时间间隔不足，提示并退出
      }

      // 更新上次执行的时间戳
      this.lastRefreshTime = now;

      // 执行刷新逻辑
      this.get();
      this.$message.success("已经是最新数据了");
    },
    getCompleteFile() {
      axios.get(getFile + this.dialogForm.fileCompletePath, { responseType: 'blob' })
        .then((response) => {
          // 创建一个隐藏的 <a> 标签用于下载
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = URL.createObjectURL(response.data); // 设置 Blob 数据的 URL
          link.download = this.dialogForm.fileCompletePath; // 设置下载文件的名称

          document.body.appendChild(link); // 将 <a> 标签添加到文档中
          link.click(); // 触发点击事件，开始下载
          document.body.removeChild(link); // 下载完成后移除 <a> 标签
          URL.revokeObjectURL(link.href); // 释放 URL 对象
        })
        .catch((error) => {
          console.error('下载失败:', error);
          this.$message.error('文件下载失败，请稍后再试');
        });
    },
    tableRowClassName({ row, rowIndex }) {
      const now = new Date();
      const endline = new Date(row.endline);
      if (endline < now && row.status === "NotSubmitted") {
        return 'warning-row';
      } else if (row.status === "Submitted") {
        return 'success-row';
      }
      return '';
    },
    get() {
      axios.get(getStudentsHomeworks)
        .then((response) => {
          if (response.data.data != null) {
            this.tableData = response.data.data;
            // this.$message.success("学生作业信息显示成功，一共[ " + this.tableData.length + " ]条数据");

            this.homeworkData = [];
            this.unCompleteData = [];

            this.tableData.forEach((student) => {
              const subjectName = student.subjectName;

              let found = false;
              for (let i = 0; i < this.homeworkData.length; i++) {
                if (this.homeworkData[i].subjectName === subjectName) {
                  this.homeworkData[i].tableData.push(student);
                  found = true;
                  break;
                }
              }
              if (!found) {
                this.homeworkData.push({
                  subjectName: subjectName,
                  tableData: [student]
                });
              }

              const now = new Date();
              const endline = new Date(student.endline);
              if (endline < now && student.status === "NotSubmitted") {
                let unCompleteFound = false;
                for (let i = 0; i < this.unCompleteData.length; i++) {
                  if (this.unCompleteData[i].subjectName === subjectName) {
                    this.unCompleteData[i].tableData.push(student);
                    unCompleteFound = true;
                    break;
                  }
                }
                if (!unCompleteFound) {
                  this.unCompleteData.push({
                    subjectName: subjectName,
                    tableData: [student]
                  });
                }
              }
            });

            this.unCompletelNums = this.unCompleteData.reduce((total, item) => total + item.tableData.length, 0);

            localStorage.setItem("isGet", "false");
            const data1 = JSON.stringify(this.unCompleteData);
            const data2 = JSON.stringify(this.homeworkData);
            localStorage.setItem("unCompleteData", data1);
            localStorage.setItem("homeworkData", data2);
          } else {
            this.$message.warning(response.data.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
          console.log(err);
        });
    },
    getClassId() {
      const userJson = localStorage.getItem("student");
      const user = JSON.parse(userJson);
      this.class_options = [];
      this.class_options.push({ value: user.classId, label: user.classId + "班" });
    },
    handleFileChange(event) {
      this.file = event.target.files[0];
    },
    uploadFile() {
      if (!this.class_value) {
        this.$message.warning("请选择班级");
        return;
      }
      if (!this.work_value) {
        this.$message.warning("请选择科目");
        return;
      }
      if (!this.form.context) {
        this.$message.warning("请输入作业内容");
        return;
      }
      if (!this.form.endline) {
        this.$message.warning("请规定截止时间");
        return;
      }
      if (!this.file) {
        this.$message.warning("请补充附件");
        return;
      }

      const formData = new FormData();
      formData.append('file', this.file);
      formData.append('classId', this.class_value);
      formData.append('homeworkId', this.work_value);
      formData.append('context', this.form.context);
      const formattedDate = this.formatDate(this.form.endline);
      this.form.endline = formattedDate;
      formData.append('endline', this.form.endline);

      axios.post(putFile, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(response => {
          if (response.data.data != null) {
            this.class_value = "";
            this.form.endline = null;
            this.form.context = "";
            this.work_value = "";
            this.$nextTick(() => {
              this.clearFileInput();
            });
            this.$message.success("作业上传成功");
            this.get();
          } else {
            this.$message.warning(response.data.msg);
          }
        })
        .catch(error => {
          console.log(error);
          this.$message.error("出错啦~~~");
        });
    },
    checkDate(event) {
      const now = new Date();
      const selectedDate = new Date(event);
      if (selectedDate < now) {
        this.$message.warning("选择的时间不能早于当前时间，请重新选择！");
        this.form.endline = null;
      }
    },
    formatDate(date) {
      if (date instanceof Date) {
        const year = date.getFullYear().toString().slice(-4);
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
      }
      return date;
    },
    clearFileInput() {
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = null;
      }
      this.file = null;
    },
    onSubmit() {
      this.uploadFile();
    },
    openDialog(row) {
      this.dialogForm = row;
      this.dialogFormVisible = true;
    },
    saveForm() {
      console.log("保存的表单数据：", this.dialogForm);
      axios.post(pubComments, this.dialogForm)
        .then((response) => {
          if (response.data.data != null) {
            this.$message.success(response.data.data);
            this.get();
          } else {
            this.$message.warning(response.data.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err);
          console.log(err);
        })
      this.dialogFormVisible = false;
      // 可以在这里调用接口将数据保存到服务器
    }
  }
}
</script>

<style scoped>
#pub_work_main {
  width: 100%;
  height: 100%;
  background-image: url("../../assets/background/background.png");
  background-size: cover;
  display: flex;
  justify-content: space-between;
}

#left,
#right {
  overflow: auto;
  width: 50%;
  height: 100%;
}

.el-select {
  margin-right: 60%;
}

::-webkit-scrollbar {
  width: 0;
}

.pub_work_form {
  margin: 10px;
  padding: 10px;
  padding-right: 20px;
  padding-bottom: 50%;
  background-color: rgba(225, 230, 237, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.uncomplete-dialog-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.el-table {
  margin-right: 10px;
  width: 700px;
}

.homework-publish {
  width: 100%;
  margin: 20px auto;
}

.completed-students {
  margin-top: 20px;
}

::v-deep .el-table .warning-row {
  background: rgb(232, 138, 138);
}

::v-deep .el-table .success-row {
  background: #7ff540;
}
</style>